import path from 'path';
import fs from 'fs';
import yaml from 'yaml';
import lodash from 'lodash'

const _path = process.cwd().replace(/\\/g, '/')

function getconfig(name) {
    const _path = process.cwd().replace(/\\/g, '/')
    let cfgyaml = `${_path}/config/${name}.yaml`
    const configData = fs.readFileSync(cfgyaml, 'utf8');
    let config = yaml.parse(configData);
    return { config };
}

export function supportGuoba() {
    return {
        pluginInfo: {
            name: `KOOK-Plugin`,
            title: 'KOOK插件',
            author: '@时雨◎星空',
            authorLink: 'https://gitee.com/TimeRainStarSky',
            link: 'https://gitee.com/TimeRainStarSky/Yunzai-KOOK-Plugin',
            isV3: true,
            isV2: false,
            description: `KOOK插件`,
            icon: 'svg-spinners:gooey-balls-2',
            iconColor: '#d19f56',
        },
        configInfo: {
            schemas: [
                {
                    component: 'Divider',
                    label: 'KOOK设置'
                },
                {
                    field: 'permission',
                    label: 'permission',
                    component: 'Input',
                },
                {
                    field: 'sendCardMsg',
                    label: 'sendCardMsg',
                    component: 'Switch',
                },
                {
                    component: 'Divider',
                    label: 'BOT设置'
                }, {
                    field: 'token',
                    label: 'Token',
                    bottomHelpMessage: '打开[KOOK开发者中心](https://developer.kookapp.cn/app)创建 Bot',
                    component: 'GTags',
                }
                
            ],
            async getConfigData() {
                let { config } = getconfig(`KOOK`)
                return config;
            },
            async setConfigData(data, { Result }) {
                // 1.读取现有配置文件
                const configFilePath = path.join(_path, 'config', 'KOOK.yaml');
                let config = {};
                if (fs.existsSync(configFilePath)) {
                    const configContent = fs.readFileSync(configFilePath, 'utf8');
                    config = yaml.parse(configContent) || {};
                }
                // 2. 更新配置对象
                for (const [keyPath, value] of Object.entries(data)) {
                    lodash.set(config, keyPath, value);
                }
                // 3. 将更新后的配置对象写回文件
                const updatedConfigYAML = yaml.stringify(config);
                fs.writeFileSync(configFilePath, updatedConfigYAML, 'utf8');
                logger.mark(`[KOOK插件:配置文件]配置文件更新`)
                return Result.ok({}, '保存成功~');
            }
        }
    }
}
